#include "deleteDir.h"
char* deleteDir(char *path)
{
	if(mh==NULL)
		return ERR_VFS_DELETEDIR_04;
	if(strcmp(path,"/")==0)
		return ERR_VFS_DELETEDIR_02;
	if(path[0]!='/')
		return ERR_VFS_DELETEDIR_01;
	int z=strlen(path);
	if(z!=1 && path[z-1]=='/')
		path[z-1]='\0';
	char dirpath[100];
	int i=strlen(path)-1;
	for(;path[i]!='/';i--);
	char *pathParent=(char*)malloc(sizeof(char)*(i+1));
	int j=0;
	for(;j<i;j++)
		pathParent[j]=path[j];
	pathParent[j]='\0';
	char *currDir=(char*)malloc(sizeof(char)*(strlen(path)-1-i+1));
	j=0;
	i++;
	for(;path[i]!='\0';j++)
	{
		currDir[j]=path[i];
		i++;
	}
	currDir[j]='\0';
	if(strcmp(pathParent,"")==0 || strcmp(pathParent," ")==0)
		pathParent="/";
	int iterDescriptors;
	strcpy(dirpath,path);
	char *tokens[20];
	i=0;	
	tokens[i]=strtok(dirpath,"/");
	while(tokens[i] != NULL)
	{
		i++;
		tokens[i]=strtok(NULL,"/");
	}
	i=0;
	
	
	nAryNode *temp = nAryRoot,*lsibling;
	
	if(nAryRoot == NULL)
	{
		return ERR_VFS_DELETEDIR_01;
	}
	if(strcmp(temp->name,"/")==0)
	{
		if(temp->child!=NULL)
			temp=temp->child;
		else
			return ERR_VFS_DELETEDIR_01;
	}
	
	if((tokens[i] != NULL)&&(nAryRoot == NULL))
	{
		return ERR_VFS_DELETEDIR_01 ;
	}
	
	while(tokens[i] != NULL && temp!=NULL)
	{
		while(strcmp(tokens[i],temp->name)!= 0 && (temp->sibling!= NULL))
		{
			lsibling = temp;
			temp = temp->sibling;
		}
		if(strcmp(tokens[i],temp->name)!=0)
		{
			return ERR_VFS_DELETEDIR_01 ;
		}
		i++;
		if((temp->child==NULL)&&(tokens[i]!=NULL))
		{
			return ERR_VFS_DELETEDIR_01 ;
		}
		if(tokens[i]==NULL)
				break;
		else
				temp=temp->child;
		
	}
	
	if(temp!=NULL && temp->child == NULL )
	{
		// Get the corresponding FD from bst
		
		descriptors *descrip = (descriptors*)malloc(sizeof(descriptors));
		descrip = (descriptors*)searchBST(dirpath);
		
		// Go to the header and change the corresponding FD from the FD list
		if(descrip!=NULL)
			return ERR_VFS_DELETEDIR_01;
		FILE *fptr = fopen(mh->fileSystemLabel,"r+b");
		int currentFileDescriptors = mh->countOfFileDescriptors;
		int maxFileDescriptors = mh->maxDescriptors;
		int noOfBlocks = maxFileDescriptors/2;
		fseek(fptr,sizeof(meta),SEEK_SET);
		while(iterDescriptors<maxFileDescriptors)
		{
			if(strcmp(h->desc[iterDescriptors].location,pathParent)==0 && strcmp(h->desc[iterDescriptors].fileName,currDir)==0)
			{
				h->desc[iterDescriptors].type = ' ';
				mh->countOfFileDescriptors=mh->countOfFileDescriptors-1;
				break;
			}
			iterDescriptors++;
		}
		int nAryRet=createnAryTree(maxFileDescriptors,h->desc);
		return "SUCCESS";
	}
	else
		return ERR_VFS_DELETEDIR_02;
	
	printf("\n");
}
